package com.tensquare.article.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tensquare.article.dao.ArticleDao;
import com.tensquare.article.pojo.Article;
import com.tensquare.entity.PageResult;
import com.tensquare.util.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @ClassName ArticleService
 * @Author guojy
 * @Date 2020/3/30 16:48
 * @Description TODO
 * @Version 1.0
 */
@Service
public class ArticleService {
    @Autowired
    private ArticleDao articleDao;
    @Autowired
    private IdWorker idWorker;

    public List<Article> findAll() {
        return articleDao.selectList(null);
    }

    public Article findById(String id) {
        return articleDao.selectById(id);
    }

    public void add(Article article) {
        article.setId(idWorker.nextId() + "");
        articleDao.insert(article);
    }

    public void update(Article article) {
        articleDao.updateById(article);
    }

    public void delete(String id) {
        articleDao.deleteById(id);
    }

    public PageResult search(Map<String,String> map, int pageNo, int pageSize) {
        // 构建分页对象
        IPage<Article> page = new Page<>(pageNo, pageSize);
        // 构建查询条件
        QueryWrapper<Article> wrapper = new QueryWrapper<>();
        // 匹配所有条件 动态sql
        for (String field : map.keySet()) {
            wrapper.eq(null!=map.get(field),field,map.get(field));
        }

        // 执行查询
        IPage<Article> page1 = articleDao.selectPage(page, wrapper);
        return  new PageResult<Article>(page1.getTotal(),page1.getRecords());
    }
}
